/*
 *  Copyright 2007 Genoworks
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License. 
 */

package com.genoworks.retriever.bigdir;

import java.io.File;
import java.util.StringTokenizer;
import java.util.TreeSet;

/**
 * A virtual {@link File} stored in
 * {@link BigDirectory}. A
 * <code>VirtualFile</code> is
 * composed with a set of
 * {@link BigFileSegment}s.
 * 
 * @author appler
 * 
 */
class BigFile {

  private String fileName = null;

  private TreeSet<BigFileSegment> segments = new TreeSet<BigFileSegment>();

  private long lastModified = System.currentTimeMillis();

  BigFile( String name ) {
    fileName = name;
  }

  String getName() {
    return fileName;
  }

  TreeSet<BigFileSegment> getSegments() {
    return segments;
  }

  void clearSegments() {
    segments.clear();
  }

  @SuppressWarnings( "nls" )
  static BigFile fromDirString( String str ) {

    //
    StringTokenizer st = new StringTokenizer( str, "," ); //$NON-NLS-1$

    //
    BigFile result = null;

    //
    if ( st.hasMoreTokens() ) {
      result = new BigFile( st.nextToken() );
      result.lastModified = Long.parseLong( st.nextToken() );
    } else {
      throw new IllegalArgumentException( "file name not found" );
    }

    //
    while ( st.hasMoreTokens() ) {
      result.segments.add( BigFileSegment.fromDirString( st.nextToken() ) );
    }

    //
    return result;
  }

  String toDirString() {
    StringBuilder result = new StringBuilder();
    // TODO B64
    result.append( fileName );
    result.append( ',' );
    result.append( String.valueOf( lastModified ) );
    for ( BigFileSegment seg : segments ) {
      result.append( ',' );
      result.append( seg.toDirString() );
    }
    return result.toString();
  }

  void addSegments( TreeSet<BigFileSegment> segs ) {
    synchronized( segments ) {
      segments.addAll( segs );
    }
  }

  long getLastModified() {
    return lastModified;
  }

  void setLastModified( long when ) {
    lastModified = when;
  }

  long getLength() {
    long length = 0L;
    for ( BigFileSegment seg : segments ) {
      length += seg.getLength();
    }
    return length;
  }

  public String toString() {
    return "BigFile{anme=" + fileName
        + ","
        + segments
        + ",lastModified="
        + lastModified
        + "}";
  }
}
